package view.code
{
	import flash.events.Event;
	import flash.events.MouseEvent;

	import iris.loader.HtmlLoader;
	import iris.loader.LoaderEvent;
	import iris.utils.IrisStringUtil;

	import mx.collections.ArrayCollection;

	import nz.co.codec.flexorm.EntityManager;
	import nz.co.codec.flexorm.criteria.Criteria;

	import orm.fantasy.TblItemPropertyVO;
	import orm.fantasy.TblItemVO;

	import spark.components.Button;

	public class CodeTransItemName extends Button
	{
		public function CodeTransItemName()
		{
			super();
		}

		private static const STEP_COUNT:int = 5;

		private var _step:int = 0;
		private var _itemList:ArrayCollection;

		protected function design_clickHandler(event:MouseEvent):void
		{
			_itemList = EntityManager.instance.findAll(TblItemPropertyVO);
			gotoNextStep();
		}

		private function gotoNextStep():void
		{
			for(var inLoop:Boolean = true; (_step < _itemList.length && _step % STEP_COUNT != 0) || inLoop; _step++, inLoop = false)
			{
				var propertyVo:TblItemPropertyVO = _itemList.getItemAt(_step) as TblItemPropertyVO;
				var url:String = "http://db.178.com/wow/cn/item/" + propertyVo.info_item_id + ".html";
				var loader:HtmlLoader = new HtmlLoader(propertyVo.info_item_id, url);
				loader.addEventListener(LoaderEvent.COMPLETE, loader_completeHandler);
				loader.load();

				trace("_step: " + _step);
//				propertyVo.info_item_id
//				trace(propertyVo.info_item_name);
			}
		}
		private var _completeCount:int;

		private function loader_completeHandler(event:LoaderEvent):void
		{
			var em:EntityManager = EntityManager.instance;
			var criteria:Criteria = em.createCriteria(TblItemPropertyVO);
			criteria.addEqualsCondition("info_item_id", event.id);
			var propertyVo:TblItemPropertyVO = em.fetchCriteria(criteria).getItemAt(0) as TblItemPropertyVO;
			var itemName:String = IrisStringUtil.intercept(event.data as String, "<title>", " - 物品", false, false);
			trace(propertyVo.info_item_name, itemName)
			propertyVo.info_item_name = itemName;
			em.save(propertyVo);

			_completeCount++;
			if(_completeCount == STEP_COUNT)
			{
				_completeCount = 0;
				gotoNextStep();
			}
		}
	}
}